package com.cyt.sys.util;

import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;

/**
 *DES加密算法工具类
 *
 * Created by dingxu on 2019/4/8.
 */
public class DESHelper {


    /**
     *
     * @Method: encrypt
     * @Description: 加密数据
     * @param data
     * @return
     * @throws Exception
     * @date 2019/4/8
     */
    public static String encrypt(String data,String password) {  //对string进行BASE64Encoder转换
        if(data==null||data.equals("")){
            return null;
        }else{
            byte[] bt = encryptByKey(data.getBytes(), password);
            BASE64Encoder base64en = new BASE64Encoder();
            String strs = new String(base64en.encode(bt));
            return strs;
        }
    }

    /**
     *
     * @Method: encrypt
     * @Description: 解密数据
     * @param data
     * @return
     * @throws Exception
     * @date 2019/4/8
     */
    public static String decryptor(String data,String password) throws Exception {
        //对string进行BASE64Encoder转换
        if(data==null||data.equals("")){
            return null;
        }else {
            sun.misc.BASE64Decoder base64en = new sun.misc.BASE64Decoder();
            byte[] bt = decrypt(base64en.decodeBuffer(data), password);
            String strs = new String(bt);
            return strs;
        }
    }

    /**
     * 加密
     * @param datasource byte[]
     * @param key String
     * @return byte[]
     */
    private static byte[] encryptByKey(byte[] datasource, String key) {
        try{
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            //创建一个密匙工厂，然后用它把DESKeySpec转换成
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            //Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES");
            //用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            //现在，获取数据并加密
            //正式执行加密操作
            return cipher.doFinal(datasource);
        }catch(Throwable e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param src byte[]
     * @param key String
     * @return byte[]
     * @throws Exception
     */
    private static byte[] decrypt(byte[] src, String key) throws Exception {
        // DES算法要求有一个可信任的随机数源
        SecureRandom random = new SecureRandom();
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(key.getBytes());
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        // 真正开始解密操作
        return cipher.doFinal(src);
    }

    //测试
    public static void main(String args[]) {
        //待加密内容
        String str = "MIICdAIBADANBgkqhkiG9w0BAQEFAASCAl4wggJaAgEAAoGBAIJDOKkhnKdMrH4CRYnHhizG2AgO\n" +
                "csgiSKkk1uwATvmTqinISheguH8A56FXClY0+BP6+hTJWtQG6DJ5XbS4ZFXT+TZFnEZsMyj1gSCp\n" +
                "DHWRBu17pW4haYTBHNhEk+h0BApTjfI2QLrMnpLqF47saQJuBM5cEXjA5YDi/a3RJseTAgMBAAEC\n" +
                "gYAuicGWe1GyW6xMoJcjcEs5eBj6V98eLVF0TJsUWc/dTqo+nzYJVvxTM4mNlME2p1nyGXp7Lqzq\n" +
                "j0Upsz6NMEt3885LgWLJmbQ/rQGYNr1P7SoYEsLKBFutVRJQI1CxIBKN8KRkwAi/EQLgW3E+Z48g\n" +
                "Y3JezzGHnxbUHgcs4IqqcQJBAL+vZf7fK2BVtVVDhUafMlb1srasB5hhwae1RLIXugQyPfCFx6JP\n" +
                "uBm5pI3Pt0zGwvYyVLvsRRi+WokWfjeIGu0CQQCt9/5rc1vEn4fGGdGck7hG7M6ayGjMA1kqgjgr\n" +
                "zymu6PpAUy17R9ryYCNc/BiETgmlfpyCNJDIYV5/N2KY/Zx/AkAGe/9+TLxh6ORWew9CIVaJnIws\n" +
                "I8up+vybGMW3JJhVVgHEZjInqny22hHX/kPcJAkqXO+C3+5CdQYJByrD5CXNAj8M6Vr4npcxAKYT\n" +
                "DdeAx3Xlza2Hz1f3zEfR39hLaBSv5pqsK4A0piCZ3IjDXfJz31bX8Y2sHDqipJde2b13nVsCQFJ0\n" +
                "vesK52/KxUj03ctTcnNfda0hesukHH9yPBhdBONGhU/6dt6XdZWnWswi26zn0moSIYsx8QMYMhD/\n" +
                "e/1fw08=\n";
        String password ="99998877";
        String result = DESHelper.encrypt(str,password);

        BASE64Encoder base64en = new BASE64Encoder();
//        String strs = new String(base64en.encode(result));

        System.out.println("加密后："+result);
        //直接将如上内容解密
        try {
            String decryResult = DESHelper.decryptor(result,password);
            System.out.println("解密后："+new String(decryResult));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }



}
